<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2019 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: Powerless < wzxaini9@gmail.com>
// +----------------------------------------------------------------------
namespace app\user\controller;

use app\member\model\MemberModel;
use app\validate\SearchValidate;
use think\Db;
use think\Exception;
use think\facade\Validate;
use cmf\controller\HomeBaseController;
use app\user\model\UserModel;
use app\user\model\PersonalModel;
use app\third\AliPay;
use app\third\WeChatPay;

class personalController extends HomeBaseController
{

    //优先执行判断登录状态

    public function _initialize()
    {
        parent::_initialize(); // TODO: Change the autogenerated stub
        $this->token = $this->request->patch('token');

        //判断token的传值
        if (isset($_SERVER["HTTP_TOKEN"])) {
            $this->user = $this->check_user_login($_SERVER["HTTP_TOKEN"]);//验证用户
        } else {
            $this->user = $this->check_user_login($this->token); //验证用户
        }
        if (!$this->user) {
            $this->ajaxResult(-1, '请登录后再试!');
        }
    }

    /*
    临时工-修改密码
    用户原密码 old_password
    用户新密码 password
    确定新密码 repassword
    */

    public function lsg_passwordReset()
    {

        //输入的数据
        $data = $this->request->param();
        $errorInfo = (new SearchValidate())->goCheck('lsg_passwordReset');
        if ($errorInfo !== true) $this->ajaxResult(-1, $errorInfo['msg'], $errorInfo['data']);
        //把需要的数据全部保存到user里面去
        $user['id'] = $this->user['user_id'];
        $user['old_password'] = $data['old_password'];
        $user['password'] = $data['password'];
        $user['repassword'] = $data['repassword'];

        //调用用户模型
        $userModel = new MemberModel();
        $log = $userModel->lsg_editPassword($user);
        //判断各种返回码
        switch ($log) {
            case 0:
                $this->ajaxResult(1, '修改密码成功!');
                break;
            case 1:
                $this->ajaxResult(-1, '两次密码不正确!');
                break;
            case 2:
                $this->ajaxResult(-1, '原密码不正确!');
                break;
            default :
                $this->ajaxReturn(['msg' => '未受理的请求', 'status' => -1]);
        }

    }

    /**
     * 图片上传
     */

    public function upload_img()
    {

        $file = $this->request->file('imgfile');
        $image_upload_limit_size = config('image_upload_limit_size');
        $validate = ['size' => $image_upload_limit_size, 'ext' => 'jpg,png,gif,jpeg'];
        $dir = ROOT_PATH . 'public/upload/personal/';
        if (!($_exists = file_exists($dir))) {
            $isMk = mkdir($dir);
        }
        $parentDir = date('Ymd');
        $info = $file->validate($validate)->move($dir, true);
        if ($info) {
            $post['head_pic'] = '/' . $dir . $parentDir . '/' . $info->getFilename();
            $return_imgs = '/upload/personal/' . $parentDir . '/' . $info->getFilename();
        } else {
            // $this->error($file->getError());//上传错误提示错误信息
            $this->ajaxReturn(['status' => -1, 'msg' => $file->getError()]);//上传错误提示错误信息
        }

        $this->ajaxReturn(['status' => 1, 'msg' => '操作成功', 'result' => $return_imgs]);
    }

    /*
    临时工-反馈
    用户token    token
    用户手机号码 mobil
    意见或建议 comment
    图片 picture
    */

    public function lsg_feedback()
    {

        //输入数据
        $data = $this->request->param();

        //没有输入意见
        if (empty($data['comment'])) {
            $this->ajaxResult(-1, '请输入您的意见与建议');
        }

        //输入手机号不对
        if (!cmf_check_mobile($data['mobile'])) {
            $this->ajaxResult(-1, '您输入的手机号码有误');
        }

        if (empty($data['picture'])) {
            $this->ajaxResult(-1, '请上传证明图片');
        }

        $insert_data = array(
            'user_id' => $this->user['user_id'],//用户id
            'comment' => $data['comment'], //评论内容
            'create_time' => time(), //评论时间
            'picture' => $data['picture'], //上传证明图片
            'mobile' => $data['mobile'], //联系电话
        );

        $db_feed = Db::table('cmf_feedback')->insert($insert_data);
        //判断是否成功入库

        $db_feed > 0 ? $this->ajaxResult(1, '反馈提交成功') : $this->ajaxResult(-1, '意见反馈没有数据请重新提交');

    }


    /*
    临时工 - 家庭地址
    * 联系人名称 nickname
    * 联系人地址 address
    * 联系人手机 mobile
    *
    */

    public function home_address()
    {

        $data = Db::table('cmf_address')
            ->where('user_id', $this->user['user_id'])
            ->field([
                'nickname',//昵称
                'mobile',//联系电话
                'my_address',//地址
                'status',//默认地址
                'id', //地址id
            ])
            ->select()
            ->toArray();

        $data > 0 ? $this->ajaxResult(1, '成功', $data) : $this->ajaxResult(-1, '没有数据');

    }

    /*
    临时工 - 新增家庭地址
    * 联系人名称 nickname
    * 联系人地址 address
    * 联系人手机 mobile
    *
    */

    public function add_address()
    {
        $data = $this->request->param();

        $status = $this->request->param('status/d', 0);

        //没有输入姓名
        if (empty($data['nickname'])) {
            $this->ajaxResult(-1, '请填写用户名称');
        }
        //手机格式问题
        if (!cmf_check_mobile($data['mobile'])) {
            $this->ajaxResult(-1, '请输入正确的手机号码');
        }
//            //没有输入地址
//            if (empty($data['my_address'])) {
//                $this->ajaxResult(-1, '详细地址必须输入');
//            }

        //工作地址
        if (!empty($data['my_address'])) {
            $address = $data['province'] . $data['city'] . $data['district'] . $data['my_address'];
            $url = 'http://restapi.amap.com/v3/geocode/geo?address=' . $address . '&key=b413542c6a53d085cc5b3466520d7e79';
            if ($result = file_get_contents($url)) {
                $result = json_decode($result, true);
                //判断是否成功
                if (!empty($result['count'])) {
                    $LongitudeLatitude = $result['geocodes']['0']['location'];
                    $longitudes = explode(',', $LongitudeLatitude);
                    $data['longitude'] = $longitudes['0'];
                    $data['latitude'] = $longitudes['1'];
                } else {
                    return false;
                }
            }
            $data['my_address'] = $address;
        }


        unset($data['token']);
        if ($status == 1) {  //更改为默认地址
            $re['id'] = Db::table('cmf_address')->where(['user_id' => $this->user['user_id'], 'status' => 1])->value('id'); //这个没有值代表用户没有设置过默认地址
            if ($re && !empty($re['address_id'])) {
                $re['status'] = 0;
                $ree = Db::table('cmf_address')->update($re);
                $data['status'] = 1;
            }

        }
        $data['create_time'] = time();
        $data['user_id'] = $this->user['user_id'];
        $insert_data = Db::table('cmf_address')->insert($data); //需要设置默认的地址表id
        $insert_data > 0 ? $this->ajaxResult(1, '新增地址成功') : $this->ajaxResult(-1, '新增失败');

    }

    /*
    临时工 - 删除家庭地址
    */

    public function del_address()
    {

        $id = $this->request->param('id'); //地址id

        $delinfo = Db::table('cmf_address')->where('id', $id)->delete();

        $delinfo > 0 ? $this->ajaxResult(1, '删除成功') : $this->ajaxResult(-1, '删除失败');
    }


    /*
    临时工 - 商家地址
    */
    public function merchant_address()
    {
        $data = $this->request->param();
        //工作地址
        if (!empty($data['address'])) {
            $address = $data['province'] . $data['city'] . $data['district'] . $data['address'];
            $url = 'http://restapi.amap.com/v3/geocode/geo?address=' . $address . '&key=b413542c6a53d085cc5b3466520d7e79';
            if ($result = file_get_contents($url)) {
                $result = json_decode($result, true);
                //判断是否成功
                if (!empty($result['count'])) {
                    $LongitudeLatitude = $result['geocodes']['0']['location'];
                    $longitudes = explode(',', $LongitudeLatitude);
                    $data['longitude'] = $longitudes['0'];
                    $data['latitude'] = $longitudes['1'];
                } else {
                    return false;
                }
            }
        }

        //添加到数据库
        $db_feed = Db::table('cmf_member')->where('id', $this->user['user_id'])->setField($data);
        //判断是否成功入库
        $db_feed > 0 ? $this->ajaxResult(1, '保存成功') : $this->ajaxResult(-1, '没有数据发生变化,请重试!');
    }

    public function merchant_address_info()
    {
        $data = Db::name('member')->where(['id'=>$this->user['user_id']])->field(['province','city','district','address','latitude','longitude'])->find();
        $this->ajaxResult(1, 'success', $data);
    }


    /*
    临时工 - 基础资料
    用户token   token
    sex 性别 0:保密 ,1:男, 2:女
    degree 学历 1:小学,2:初中,3:高中,4:大专 5:本科  6硕士 7博士及以上
    nickname 昵称
    age 年龄
    sex 性别
    job 职业
    enterprise 在职企业
    telephone 联系电话
    user_email 用户邮箱
    */
    public function lsg_basal()
    {

        //输入数据
        $data = $this->request->param();
        //判断是不是post请求
        if ($this->request->isPost()) {
            //昵称
            if (!empty($data['nickname'])) {
                $up['user_nickname'] = $data['nickname'];
            }
            //年龄
            if (!empty($data['age'])) {
                $up['age'] = $data['age'];
            }
            //性别
            if (!empty($data['sex'])) {
                $up['sex'] = $data['sex'];
            }
            //学历
            if (!empty($data['degree'])) {
                $up['degree'] = $data['degree'];
            }
            //主要职业
            if (!empty($data['job'])) {
                $up['job'] = $data['job'];
            }
            //在职企业
            if (!empty($data['enterprise'])) {
                $up['enterprise'] = $data['enterprise'];
            }
            //联系电话
            if (!empty($data['telephone'])) {
                $up['telephone'] = $data['telephone'];
            }
            //邮箱
            if (!empty($data['user_email'])) {
                $up['user_email'] = $data['user_email'];
            }


            $db_feed = Db::table('cmf_member')->where('id', $this->user['user_id'])->setField($up);

            //判断是否成功保存
            $db_feed > 0 ? $this->ajaxResult(1, '保存成功') : $this->ajaxResult(-1, '没有数据');


        }
    }

    /*
   * 临时工 - 展示基础资料
   */

    public function show_basal()
    {

        $where = ['m.id' => $this->user['user_id']];

        $info = Db::table('cmf_member')
            ->alias('m')
            ->where($where)
            ->field([
                'm.user_nickname',
                'm.sex',
                'm.degree',
                'm.age',
                'm.job',
                'm.enterprise',
                'm.telephone',
                'm.user_email',
                'm.hx_uniqid',
                's.business_status',//认证状态
                //                "(if(s.business_status=0,'验证','未验证')) as ty ",//方法二
                //手机
                //工商认证
                'm.address',//商户地址
            ])
            ->join('cmf_personal_check s', 'm.id = s.uid', 'LEFT')
            ->find();
        if ($info['business_status'] == 1) {
            $info['type'] = '验证';
        } else {
            $info['type'] = '未验证';
        }

        if ($info > 1) {
            $this->ajaxResult(1, '请求成功', $info);
        }
        $this->ajaxResult(-1, '请求失败');
    }


    /*
    * 临时工 - 我的标签
    label_name 标签名
    */

    public function lsg_label()
    {

        //输入的数据
        $data = input('label_name/a');
        //更新某个字段
        if (!empty($data)) {
            //入库状态
            $db_feed = Db::table('cmf_member')->where('id', $this->user['user_id'])->update(['label_name' => json_encode($data, JSON_UNESCAPED_UNICODE)]);
        }
        //判断是否成功保存
        $db_feed > 0 ? $this->ajaxResult(1, '保存成功') : $this->ajaxResult(-1, '没有数据');
    }

    /*
    * 临时工 - 我的标签
    label_name 标签名
    */
    public function show_label()
    {
        $where = ['id' => $this->user['user_id']];
        $info = Db::table('cmf_member')
            ->where($where)
            ->field([
                'user_nickname',
                'id',
                'label_name',
            ])->find();
        if (!empty($info['label_name'])) {
            $info['label_name'] = json_decode($info['label_name']);
        } else {
            $info['label_name'] = [];
        }
        if ($info > 1) {
            $this->ajaxResult(1, '请求成功', $info);
        }
        $this->ajaxResult(-1, '请求失败');
    }

    /*
   * 临时工 - 我的工种
   label_name 工种名
   */
    public function show()
    {

        $where = ['user_id' => $this->user['user_id']];


        $info = Db::table('cmf_user_profession')
            ->where($where)
            ->field([
                'job_id',
                'profession_name',
            ])->select()->toArray();

        if ($info > 1) {
            $this->ajaxResult(1, '请求成功', $info);
        }
        $this->ajaxResult(-1, '请求失败');
    }


    /*
    * 临时工 - 我的工种
     用户id user_id
     工种名称 profession_name
     工种价格 profession_price
    */

    public function lsg_profession()
    {

        //输入的数据
        $data = $this->request->param();
        //工种名称必填
        if (empty($data['profession_name'])) {
            $this->ajaxResult('-1', '工种名称必填!');
        }
        //工种价格
        if (empty($data['profession_price'])) {
            $this->ajaxResult('-1', '价格必填!');
        }
        //数据
        $insert_data = array(
            'user_id' => $this->user['user_id'], // 用户id
            'profession_name' => $data['profession_name'], //工种名称
            'profession_price' => $data['profession_price'],//工种价格
        );
        //入库操作
        $db_feed = Db::table('cmf_user_profession')->insert($insert_data);

        //判断是否成功保存
        $db_feed > 0 ? $this->ajaxResult(1, '保存成功') : $this->ajaxResult(-1, '没有输入其他工种,请重试!');

    }

    /**
     * 修改图片
     * @throws \think\Exception
     */
    public function editImg()
    {
        $user = $this->user;
        $params = $this->request->param();

        $data = [
            'avatar' => isset($params['avatar']) ? $params['avatar'] : '',
            'show_picture' => isset($params['show_picture']) ? json_encode($params['show_picture']) : ''
        ];
        $res = Db::table('cmf_member')->where(['id' => $user['id']])->update($data);
        if (false === $res) $this->ajaxResult(0, '保存失败');
        $this->ajaxResult(1, '保存成功');
    }

    /**
     * 展示个人信息图片
     * @throws \think\exception\DbException
     */
    public function editShowImg()
    {
        $user = $this->user;
        $info = Db::table('cmf_member')->where(['id' => $user['id']])->field(['avatar', 'show_picture'])->find();
        if (!empty($info) && $info['show_picture']) $info['show_picture'] = json_decode($info['show_picture']);
        $this->ajaxResult(1, '请求成功', $info);
    }

    /*
    * 临时工 - 展示我的工种
    */
    public function show_profession()
    {

        $where = ['user_id' => $this->user['user_id']];


        $info = Db::table('cmf_user_profession')
            ->where($where)
            ->field([
                'id',
                'profession_name',
                'profession_price',
            ])->select()->toArray();

        if ($info > 1) {
            $this->ajaxResult(1, '请求成功', $info);
        }
        $this->ajaxResult(-1, '请求失败');

    }


    /*
   临时工 - 删除工种
   */

    public function del_profession()
    {

        $id = $this->request->param('id');

        $delinfo = Db::table('cmf_user_profession')->where('id', $id)->delete();

        $delinfo > 0 ? $this->ajaxResult(1, '删除成功') : $this->ajaxResult(-1, '删除失败');
    }


    /*
    * 临时工 - 日期设定
    用户id user_id
    工种名称 profession_name
    工种价格 profession_price
    */

    public function lsg_setTime()
    {
        // $time=json_decode( "[1562256000,1562083200]"); 到时候取数据就这样取给前端就可以 这样就可以传多个时间
        //  var_dump($time);exit;
        $time = $this->request->param('disabled_time/a');


        $disabled_time = [];

        foreach ($time as $k => $v) {
            $disabled_time[] = $v;
        }
        $up['disabled_time'] = json_encode($disabled_time);

        //入库状态
        $db_feed = Db::table('cmf_member')->where('id', $this->user['user_id'])->setField($up);

//            echo Db::table('cmf_user')->getLastSql();

        //判断是否成功保存
        $db_feed > 0 ? $this->ajaxResult(1, '保存成功') : $this->ajaxResult(-1, '请不要重复提交!');

    }


    /*
    * 临时工 - 个人说明
     * 个人说明 content
    */
    public function lsg_content()
    {

        //输入数据
        $data = $this->request->param();
        if (!empty($data['content'])) {

            $up['content'] = $data['content'];

            $db_feed = Db::table('cmf_member')->where('id', $this->user['user_id'])->update($up);


            //判断是否成功保存
            $db_feed > 0 ? $this->ajaxResult(1, '保存成功!') : $this->ajaxResult(-1, '请不要重复提交!');

        }


    }


    public function look_more()
    {


        $re = Db::table('cmf_member')
            ->where('id', $this->user['user_id'])
            ->field([
                'modify_q',
                'shipping_q',
                'modify_pay'
            ])
            ->find();

        if ($re > 1) {
            $this->ajaxResult(1, '请求成功', $re);
        }
        $this->ajaxResult(-1, '请求失败');
    }


    /*
    * 临时工 - 次数设置
     * 可修改次数 默认0 最大5 modify_q
     * 单日最多接单次数 默认1 最大5 shipping_q
     * 付费修改 默认不开启0 开启1 modify_pay
    */

    public function lsg_more()
    {


        //接收数据
        $data = $this->request->param();
        //修改次数超过最大
        if ($data['modify_q'] > 5) {
            $this->ajaxResult(-1, '已超过最大可修改次数');
        }
        //接单次数超过最大
        if ($data['shipping_q'] > 5) {
            $this->ajaxResult(-1, '已超过单日最多接单数');
        }


        //数据
        $insert_data = array(
            'modify_q' => $data['modify_q'], //可修改次数
            'shipping_q' => $data['shipping_q'],//单日最大接单
            'modify_pay' => $data['modify_pay'],//付费修改
        );

        //操作数据库
        $db_feed = Db::table('cmf_member')->where('id', $this->user['user_id'])->update($insert_data);

        //判断是否成功保存
        if(false === $db_feed) $this->ajaxResult(-1, '保存失败!');
        $this->ajaxResult(1, '保存成功!');
    }


    /*
    * 临时工 - 展示我的工种
    */
    public function show_status()
    {

        $where = ['id' => $this->user['user_id']];

        $info = Db::table('cmf_member')
            ->where($where)
            ->field([
                'work_status',
            ])->find();


        $infos = explode('|', $info['work_status']);

        if ($info > 1) {
            $this->ajaxResult(1, '请求成功', $infos);
        }
        $this->ajaxResult(-1, '请求失败');

    }


    /*
     * 临时工 - 工作方式
     * 工作方式状态 work_status 默认0线上 1线下
    */

    public function work_status()
    {

        $work_status = $this->request->param('work_status/a');

        if (in_array(1, $work_status)) {


            //先查出有没有是否已通过验证
            $id = $this->user['user_id'];
            $db_feed = Db::table('cmf_personal_check')
                ->where('uid', $id)
                ->value('personal_status');
            //判断是否成功保存
            $db_feed == 0 && $this->ajaxResult(-1, '未认证,不能开启线下工作功能');
        }

        $work_status = implode('|', $work_status);
        $up['work_status'] = $work_status;
        //操作数据库
        $db_feed = Db::table('cmf_member')->where('id', $this->user['user_id'])->update($up);

        //判断是否成功保存
        $db_feed >= 0 ? $this->ajaxResult(1, '保存成功!') : $this->ajaxResult(-1, '请不要重复提交!');
    }

    /*
     * 临时工 - 认证
     * 用户照片 image
     * 身份证正面    faceid_image
     * 身份证反面    backid_image
     * 手持身份证    handid_image
     * 个人认证状态 personal_status 0:未审核 1:审核通过 2:审核不通过
     * 个人认证保证金 personal_deposit
     * 个体户执照   personal_licence
     * 工商执照     business_licence
     * 工商认证状态 business_status 0:未审核 1:审核通过 2:审核不通过
     * 工商认证保证金 licence_deposit
     * 0:个人认证 1:工商验证 type
    */
    public function lsg_Authentication()
    {

        $data = $this->request->param();

        //个人认证
        if ($data['type'] == 0) {

            if (empty($data['image'])) {
                $this->ajaxResult(-1, '请上传图片');
            }

            if (empty($data['faceid_image'])) {
                $this->ajaxResult(-1, '请上传身份证正面');
            }

            if (empty($data['backid_image'])) {
                $this->ajaxResult(-1, '请上传身份证反面');
            }

            if (empty($data['handid_image'])) {
                $this->ajaxResult(-1, '请上传手持身份证');
            }

            $data_array = array(
                'user_id' => $this->user['id'], //用户id
                'image' => $data['image'], //用户照片
                'faceid_image' => $data['faceid_image'], //身份正面
                'backid_image' => $data['backid_image'], //身份反面
                'handid_image' => $data['handid_image'], //手持身份
                'personal_upload_date' => time(),//用户上传图片时间
            );

            $updata_user_personalId = Db::table('cmf_personal_check')->insert($data_array);

            $updata_user_personalId > 0 ? $this->ajaxResult(1, '审核中,请耐心等待') : $this->ajaxResult(-1, '提交失败请重新提交');


            //工商验证
        } else if ($data['type'] == 1) {

            //查出个人认真
            $status = new PersonalModel();
            $personal_status = $status->personal_reviews($this->user['user_id']);


            //判断有没有通过个人认证
            if ($personal_status['personal_status'] > 0) {

                if (empty($data['personal_licence']) && empty($data['business_licence'])) {
                    $this->ajaxResult(-1, '没有上传任何图片');
                }
                //   个体户执照
                if ($data['image_type'] == 0) {

                    //  企业执照
                } else if ($data['image_type'] == 1) {

                }


            } else {
                $this->ajaxResult(-1, '未有效个人认证,请认证');
            }

        }

    }

    // 个人认证
    public function Personal_certification()
    {
        $data = $this->request->param();

        //个人图片
        if (empty($data['image'])) {
            $this->ajaxResult(-1, '请个人上传图片');
        } else {
            $insert['image'] = $data['image'];
        }

        //身份证正面
        if (empty($data['faceid_image'])) {
            $this->ajaxResult(-1, '请上传身份证正面');
        } else {
            $insert['faceid_image'] = $data['faceid_image'];
        }

        //身份证反面
        if (empty($data['backid_image'])) {
            $this->ajaxResult(-1, '请上传身份证反面');
        } else {
            $insert['backid_image'] = $data['backid_image'];
        }

        //手持证件
        if (empty($data['handid_image'])) {
            $this->ajaxResult(-1, '请上传手持身份证');
        } else {
            $insert['handid_image'] = $data['handid_image'];
        }

        $insert['personal_upload_date'] = time();

        $exist = Db::table('cmf_personal_check')->where(['uid' => $this->user['user_id']])->find();
        if ($exist) {
            $params = [
                'personal_status' => 0,
                'personal_pay' => 0,
                'personal_deposit' => 0 // 提交需重新支付
            ];
            $insert = array_merge($insert, $params);
            $res = Db::table('cmf_personal_check')->where(['id'=>$exist['id']])->update($insert);
            if(false === $res) $this->ajaxResult(-1, '提交失败请重新提交');
        }else{
            $insert['uid'] = $this->user['user_id'];
            $updata_user_personalId = Db::table('cmf_personal_check')->insert($insert);
            if (!$updata_user_personalId) $this->ajaxResult(-1, '提交失败请重新提交');
        }

        $this->ajaxResult(1, '审核中,请耐心等待');
    }

    // 认证状态
    public function certificationCheck()
    {
        $check_status = [
            '未审核',
            '审核通过',
            '审核未通过'
        ];
        $pay_status = [
            '未支付',
            '已支付'
        ];

        $exist = Db::name('personal_check')->where(['uid' => $this->user['user_id']])->field([
            'id', 'image', 'faceid_image', 'backid_image', 'handid_image', 'personal_status', 'business_licence', 'business_status', 'personal_pay', 'business_pay'
        ])->find();
        if (empty($exist)) $this->ajaxResult(-1, '暂未认证');

//        $exist['personal_status'] = $check_status[$exist['personal_status']];
//        $exist['business_status'] = $check_status[$exist['business_status']];
//        $exist['personal_pay'] = $pay_status[$exist['personal_pay']];
//        $exist['business_pay'] = $pay_status[$exist['business_pay']];

        $this->ajaxResult(1, 'success', $exist);
    }

    // 修改认证
    public function certificationEdit()
    {
        $user = $this->user;
        $param = $this->request->param();
        $errorInfo = (new SearchValidate())->goCheck('certificationEdit', $param);
        if ($errorInfo !== true) $this->ajaxResult(-1, $errorInfo['msg'], $errorInfo['data']);

        $exist = Db::name('personal_check')->where([
            'uid' => $user['user_id']
        ])->find();
        if (!$exist || empty($exist)) $this->ajaxResult(-1, '未提交认证状态');

        $nowTime = time();
        switch ($param['type']) {
            case 0:
                // 个人
                $errorInfo = (new SearchValidate())->goCheck('certificationEdit_personal', $param);
                if ($errorInfo !== true) $this->ajaxResult(-1, $errorInfo['msg'], $errorInfo['data']);
                $data = [
                    'image' => $param['image'],
                    'faceid_image' => $param['faceid_image'],
                    'backid_image' => $param['backid_image'],
                    'handid_image' => $param['handid_image'],
                    'personal_upload_date' => $nowTime,
                    'personal_status' => 0,
                    'personal_pay' => 0,
                    'personal_deposit' => 0 // 提交需重新支付
                ];

                break;
            case 1:
                // 工商
                $errorInfo = (new SearchValidate())->goCheck('certificationEdit_business', $param);
                if ($errorInfo !== true) $this->ajaxResult(-1, $errorInfo['msg'], $errorInfo['data']);
                $data = [
                    'business_licence' => $param['business_licence'],
                    'business_upload_date' => $nowTime,
                    'business_status' => 0,
                    'business_pay' => 0,
                    'business_deposit' => 0 // 提交需重新支付
                ];

                break;
            default:
                $this->ajaxResult(-1, '类型错误');
                break;
        }

        try {
            Db::startTrans();

            $result = Db::name('personal_check')->where([
                'uid' => $user['user_id'],
                'id' => $exist['id']
            ])->update($data);
            if (false === $result) throw new Exception('personal_check update fail', 130602);

            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->ajaxResult(-1001, $e->getMessage());
        }

        $this->ajaxResult(1, 'success');
    }

    /**
     *  保证金金额
     */
    public function marginFee()
    {
        $param = $this->request->param();
        $errorInfo = (new SearchValidate())->goCheck('marginFee');
        if ($errorInfo !== true) $this->ajaxResult(-1, $errorInfo['msg'], $errorInfo['data']);

        switch ($param['type']) {
            case 0:
                $config = parent::getDbConfig('personal_certification_cost');
//                $bond = Db::table('cmf_personal_check')->where('uid', $this->user['user_id'])->field('personal_deposit')->find()['personal_deposit'];
                if (empty($config)) $this->ajaxResult(-1, '尚未设定个人认证费用，请联系平台工作人员');
                $money = $config['value'];
                break;
            case 1:
                $config = parent::getDbConfig('enterprise_certification_cost');
//                $bond = Db::table('cmf_personal_check')->where('uid', $this->user['user_id'])->field('business_deposit')->find()['business_deposit'];
                if (empty($config)) $this->ajaxResult(-1, '尚未设定个人认证费用，请联系平台工作人员');
                $money = $config['value'];
                break;
            default:
                $this->ajaxResult(-1, '类型错误');
                break;
        }

        $this->ajaxResult(1, 'success', ['money' => $money]);
    }

    // 个人保证金
    public function userMarginFee()
    {
        $param = $this->request->param();
        $errorInfo = (new SearchValidate())->goCheck('marginFee');
        if ($errorInfo !== true) $this->ajaxResult(-1, $errorInfo['msg'], $errorInfo['data']);

        $bond = Db::table('cmf_personal_check')->where('uid', $this->user['user_id'])->field(['personal_deposit','business_deposit'])->find();
        if(!$bond || empty($bond)) $money = 0;
        else {
            switch ($param['type']) {
                case 0:
                    $money = $bond['personal_deposit'];
                    break;
                case 1:
                    $money = $bond['business_deposit'];
                    break;
                case 2:
                default:
                    $money = $bond['personal_deposit'] + $bond['business_deposit'];
                    break;
            }
        }

        $this->ajaxResult(1, 'success', ['money' => $money]);
    }

    /**
     * 支付保证金
     */
    public function certificationMargin()
    {
        $param = $this->request->param();
        $errorInfo = (new SearchValidate())->goCheck('certificationMargin');
        if ($errorInfo !== true) $this->ajaxResult(-1, $errorInfo['msg'], $errorInfo['data']);

        $exist = Db::name('personal_check')->where(['uid' => $this->user['user_id']])->find();
        if (empty($exist)) $this->ajaxResult(-1, '请先提交认证');

        switch ($param['type']) {
            case 0:
                if ($exist['personal_status'] != 1) $this->ajaxResult(-1, '个人认证资料尚未上传，未审核，或审核未通过');
//                if ($exist['personal_pay'] == 1) $this->ajaxResult(-1, '您已支付保证金');
//                $config = parent::getDbConfig('personal_certification_cost');
//                if (empty($config)) $this->ajaxResult(-1, '尚未设定认证费用，请联系平台工作人员');
//                $money = $config['value'];
//                $money = 9.9;
                break;
            case 1:
                if ($exist['business_status'] != 1) $this->ajaxResult(-1, '企业认证资料尚未上传，未审核，或审核未通过');
//                if ($exist['business_pay'] == 1) $this->ajaxResult(-1, '您已支付保证金');
//                $config = parent::getDbConfig('enterprise_certification_cost');
//                if (empty($config)) $this->ajaxResult(-1, '尚未设定认证费用，请联系平台工作人员');
//                $money = $config['value'];
//                $money = 199;
                break;
            default:
                $this->ajaxResult(-1, '类型错误');
                break;
        }

//        if($money > $param['money']) $this->ajaxResult(-1, '请存入足够的保证金');

        if ($param['pay_type'] == 0) {
            if (empty($this->user['user_pass'])) $this->ajaxResult(-1, '请先设置密码');
            if (!isset($param['pass']) || empty($param['pass'])) $this->ajaxResult(-1, '请输入支付密码');
            if (cmf_password($param['pass']) != $this->user['user_pass']) $this->ajaxResult(-1, '支付密码不对，请重新输入');
            if ($this->user['balance'] < $param['money']) $this->ajaxResult(-1, '余额不足');
        }

        $model = new PersonalModel();
        $data = [
            'user_id' => $this->user['user_id'],
            'money' => $param['money']<=0?0.01:$param['money'],
            'type' => $param['type'],
            'pay_type' => $param['pay_type'],
            'base_url' => $this->request->domain()
        ];
        $result = $model->add_order($data);
        if ($result['code'] != 200) $this->ajaxResult(-1, $result['result']);

        $this->ajaxResult(1, 'success', $result['result']);
    }

    /*
    * 临时工 - 工商认证
    */
    public function Business_Certification()
    {
        $data = $this->request->param();

        //查出个人认真
        $status = new PersonalModel();
        $personal_status = $status->personal_reviews($this->user['user_id']);

        //判断有没有通过个人认证
        if ($personal_status['personal_status'] != 1) {
            $this->ajaxResult(-1, '未有效个人认证,请认证');
        } else {
            if (empty($data['business_licence'])) {
                $this->ajaxResult(-2, '请上传个人或工商执照');
            } else {
                $insert['business_licence'] = $data['business_licence'];
            }

            $insert['business_upload_date'] = time();
            $params = [
                'business_status' => 0,
                'business_pay' => 0,
                'business_deposit' => 0 // 提交需重新支付
            ];
            $insert = array_merge($insert, $params);

            $business_licence = Db::table('cmf_personal_check')->where(['uid'=>$this->user['user_id']])->update($insert);
            if (false === $business_licence) $this->ajaxResult(-1, '提交失败请重新提交');
            $this->ajaxResult(1, '审核中,请耐心等待');
        }
    }

    // 检查认证状态
    public function checkCertification()
    {
        $exist = Db::table('cmf_personal_check')->where(['uid' => $this->user['user_id']])->order('id', 'desc')->find();
        if (!$exist || ($exist['personal_status'] != 1)) $this->ajaxResult(-1, '未有效个人/工商认证,请认证');
        $this->ajaxResult(1, 'success');
    }

    //临时工 - 上传头像
    public function avatar()
    {

        $data = $this->request->param();

        $up['avatar'] = $data['avatar'];

        $db_feed = Db::table('cmf_member')->where('id', $this->user['user_id'])->setField($up);

        $db_feed > 0 ? $this->ajaxResult(1, '保存成功') : $this->ajaxResult(-1, '保存失败请重新提交');


    }

    //临时工 - 展示头像
    public function show_avatar()
    {
        $where = ['id' => $this->user['user_id']];

        $fansNum = Db::table('cmf_fans')->where('follow_id', $this->user['user_id'])->count();
        $followNum = Db::table('cmf_fans')->where('user_id', $this->user['user_id'])->count();
        $personal_status = Db::table('cmf_personal_check')->where('uid', $this->user['user_id'])->field('personal_status')->find()['personal_status'];


        $info = Db::table('cmf_member')
            ->where($where)
            ->field([
                'avatar',
                'user_nickname',
                'balance'
            ])->find();

        $info['followNum'] = $followNum;
        $info['fansNum'] = $fansNum;
        $info['personal_status'] = $personal_status;

        if ($info > 1) {
            $this->ajaxResult(1, '请求成功', $info);
        }
        $this->ajaxResult(-1, '请求失败');

    }


    //临时工 - 上传展示图片
    public function lsg_showpicture()
    {

        $data = $this->request->param();

        $up['show_picture'] = json_encode($data['show_picture']);

        $db_feed = Db::table('cmf_member')->where('id', $this->user['user_id'])->setField($up);

        $db_feed > 0 ? $this->ajaxResult(1, '保存成功') : $this->ajaxResult(-1, '保存失败请重新提交');


    }

    //微信绑定
    function bindWx()
    {
        $user = $this->user;
        if ($user['openid']) $this->ajaxResult(-1, '已经绑定过微信了');
        $param = request()->param();
        if (!isset($param['openid']) || !$param['openid']) $this->ajaxResult(-1, '参数错误');
        $memberModel = Db::name('member');
        $where = ['id' => $user['user_id']];
        $update = ['openid' => $param['openid']];
        $rs = $memberModel->where($where)->update($update);
        if ($rs) $this->ajaxResult(1, '绑定成功');
        $this->ajaxResult(-1, '绑定失败');
    }

    //微信解绑
    function relieveWx()
    {
        $user = $this->user;
        if (!$user['openid']) $this->ajaxResult(-1, '未绑定微信');
        $memberModel = Db::name('member');
        $where = ['id' => $user['user_id']];
        $update = ['openid' => ''];
        $rs = $memberModel->where($where)->update($update);
        if ($rs) $this->ajaxResult(1, '解绑成功');
        $this->ajaxResult(-1, '解绑失败');
    }

    //支付宝绑定
    function bindAli()
    {
        $user = $this->user;
        if ($user['ali_phone']) $this->ajaxResult(-1, '已经绑定过支付宝了');
        $param = request()->param();
        if (!isset($param['ali_phone']) || !$param['ali_phone']) $this->ajaxResult(-1, '参数错误');
        $memberModel = Db::name('member');
        $where = ['id' => $user['user_id']];
        $update = ['ali_phone' => $param['ali_phone']];
        $rs = $memberModel->where($where)->update($update);
        if ($rs) $this->ajaxResult(1, '绑定成功');
        $this->ajaxResult(-1, '绑定失败');
    }

    //支付宝解绑
    function relieveAli()
    {
        $user = $this->user;
        if (!$user['ali_phone']) $this->ajaxResult(-1, '未绑定过支付宝了');
        $memberModel = Db::name('member');
        $where = ['id' => $user['user_id']];
        $update = ['ali_phone' => ''];
        $rs = $memberModel->where($where)->update($update);
        if ($rs) $this->ajaxResult(1, '解绑成功');
        $this->ajaxResult(-1, '解绑失败');
    }

    //我的钱包
    function myWallet()
    {
        $user = $this->user;
        $this->ajaxResult(1, 'success', $user['balance']);
    }

    //金额明细
    function balanceDetail()
    {
        $user = $this->user;
        $accountDb = Db::name('member_account_log');
        $field = 'value,value_type,type,remark,from_unixtime(`create_time`, "%Y-%m-%d") create_time';
        $where = ['user_id' => $user['user_id']];
        $list = $accountDb->field($field)->where($where)->page($this->currentPage, $this->pageSize)->select();
        $total = $accountDb->where($where)->count();
        $data = [
            'list' => $list,
            'total' => $total,
            'page' => $this->currentPage,
            'pageSize' => $this->pageSize,
            'totalPage' => ceil($total / $this->pageSize),
        ];
        $this->ajaxResult(1, 'success', $data);
    }

    //提现
    function withdrawDeposit()
    {
        $user = $this->user;
        $param = request()->param();
        $fee = Db::name('config')->where(['name' => 'withdraw_rate'])->value('value');  //手续费
        if (!isset($param['user_paypass'])) $this->ajaxResult(-1, '支付密码必须');
        if (!$user['user_paypass']) $this->ajaxResult(-1, '请先设置支付密码');

        $flag = cmf_compare_password($param['user_paypass'], $user['user_paypass']);
        if (!$flag) $this->ajaxResult(-1, '支付密码错误');
        if (!isset($param['type'])) $this->ajaxResult(-1, '提现类型错误');
        //计算最低提现金额
        //$minMoney = bcdiv( 0.1, (1-$fee), 2 );
        if (!isset($param['money']) || $param['money'] * 100 < 100) $this->ajaxResult(-1, "提现金额必须大于1元");
        if ($param['money'] > $user['balance']) $this->ajaxResult(-1, '提现金额不足');
        $rs = false;
        $param['money'] = round($param['money'] - $param['money'] * $fee, 2);
        switch ($param['type']) {
            case 'wx':
                if (!$user['openid']) $this->ajaxResult(-1, '请先绑定微信');
                $data = [
                    'order_sn' => date('YmdHis') . rand(10000, 99999),
                    'order_title' => '企业转账',
                    'trans_amount' => 0.1,
                    're_user_name' => $user['user_nickname'],
                    'openid' => $user['openid']
                ];
                $rs = (new WeChatPay())->transfer($data);
                break;
            case 'ali':
                if (!$user['ali_phone']) $this->ajaxResult(-1, '请先绑定支付宝');
                $data = [
                    'order_sn' => date('YmdHis') . rand(10000, 99999),
                    'user' => 13005786153,
                    'order_title' => '企业转账',
                    'trans_amount' => 0.1,
                    'user_id' => $user['user_id']
                ];
                $rs = (new AliPay())->transfer($data, '1');
                break;
            default:
                $this->ajaxResult(-1, '提现类型错误');
                break;
        }
        if ($rs) $this->ajaxResult(1, '提现成功');
        $this->ajaxResult(0, $rs);
    }

}